<template>
  <div class="article-page">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>
          <el-button
            @click="openDrawer('add')"
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
          >
            添加面经
          </el-button>
        </div>
      </template>
      <el-table :data="list" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>
        <el-table-column prop="creator" label="作者" width="165">
        </el-table-column>
        <el-table-column prop="likeCount" label="点赞" width="163">
        </el-table-column>
        <el-table-column prop="views" label="浏览量" width="163">
        </el-table-column>
        <el-table-column prop="createdAt" label="更新时间" width="200">
        </el-table-column>
        <el-table-column label="操作">
          <!-- 作用域插槽 -->
          <template #default="{ row }">
            <div class="actions">
              <i
                class="el-icon-view"
                @click="openDrawer('preview', row.id)"
              ></i>
              <i
                class="el-icon-edit-outline"
                @click="openDrawer('edit', row.id)"
              ></i>
              <i class="el-icon-delete" @click="del(row.id)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination
        @size-change="handleSizeChange"                   每页显示的条数改变时触发
        @current-change="handleCurrentChange"             当前页数改变时触发
        :current-page="currentPage4"                      当前的页数
        :page-sizes="[100, 200, 300, 400]"                每页显示的条数的选项
        :page-size="100"                                  控制每页显示的条数
        layout="total, sizes, prev, pager, next, jumper"  用来给分页器布局
        :total="400">                                     总的条数
      </el-pagination> -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.current"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="q.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 抽屉组件 -->
    <el-drawer
      size="50%"
      :title="drawerTitle"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <div v-if="drawerType === 'preview'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>

      <el-form v-else ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- 单独对表单里面的某一项进行校验 -->
          <quillEditor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quillEditor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">确认</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  addArticle,
  delArticle,
  getArticleDetail,
  getArticles,
  updateArticle
} from '@/api/article'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      q: {
        current: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      drawer: false, // 控制抽屉组件的显示和隐藏
      drawerType: ''
    }
  },
  async created () {
    // const res = await getArticles(this.q)
    // // console.log(res)
    // this.list = res.data.rows
    // this.total = res.data.total
    this.loadData()
  },
  methods: {
    async loadData () {
      const res = await getArticles(this.q)
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    async del (id) {
      // console.log(id)
      const res = await delArticle(id)
      // console.log(res)
      if (res.code !== 10000) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.loadData()
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.q.current = 1
      // 改变每页显示的条数，重新发送 ajax 请求
      this.q.pageSize = val
      this.loadData()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      // 改变当前页数，重新发送 ajax 请求
      this.q.current = val
      this.loadData()
    },
    async openDrawer (type, id) {
      // console.log(type, id)
      this.drawer = true
      this.drawerType = type
      if (type !== 'add') {
        const res = await getArticleDetail(id)
        // console.log(res)
        this.form = res.data
      }
    },
    handleClose () {
      if (this.drawerType !== 'preview') {
        // 清空表单 只能清空带有 prop 属性的表单项
        this.$refs.form.resetFields()
      }
      // 手动重置
      this.form = {
        stem: '',
        content: ''
      }
      this.drawer = false
    },
    async submit () {
      try {
        await this.$refs.form.validate()
        // console.log(123)
        if (this.drawerType === 'add') {
          await addArticle(this.form)
          // console.log(res)
          this.$message.success('添加成功')
        } else {
          const { id, stem, content } = this.form
          await updateArticle({ id, stem, content })
          this.$message.success('编辑成功')
        }
        this.q.current = 1
        // 重新渲染页面
        this.loadData()
        // 关闭抽屉
        this.handleClose()
      } catch (error) {
        // console.log(error)
        this.$message.warning(error.response.data.message)
      }
    }
  },
  computed: {
    drawerTitle () {
      let tiltle
      if (this.drawerType === 'add') tiltle = '添加面经'
      if (this.drawerType === 'preview') tiltle = '面经预览'
      if (this.drawerType === 'edit') tiltle = '面经编辑'
      return tiltle
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
